package com.example.kai.uno;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Register extends AppCompatActivity {
    private MyDBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        dbHelper = new MyDBHelper(this,"UserStore.db",null,1);
        Button botton3=findViewById(R.id.button4);
        final EditText editText=findViewById(R.id.editText5);
        botton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText3=findViewById(R.id.editText3);
                EditText editText4=findViewById(R.id.editText4);
                String newname =editText3.getText().toString();
                String password=editText4.getText().toString();
                if(editText.length()==0||editText3.length()==0||editText4.length()==0)
                    Toast.makeText(Register.this,"用户名或密码为空",Toast.LENGTH_SHORT).show();
                else {
                if(editText.getText().toString().equals(editText4.getText().toString())) {
                    if (CheckIsDataAlreadyInDBorNot(newname)) {
                        Toast.makeText(Register.this, "该用户名已被注册，注册失败", Toast.LENGTH_SHORT).show();
                    } else {
                        if (register(newname, password)) {
                            Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(Register.this, Login.class);
                            startActivity(intent);
                        }
                    }
                }
                else
                    Toast.makeText(Register.this,"两次密码不一致",Toast.LENGTH_SHORT).show();
            }
        }});
    }
    //向数据库插入数据
    public boolean register(String username,String password){
        SQLiteDatabase db= dbHelper.getWritableDatabase();

        ContentValues values=new ContentValues();
        values.put("name",username);
        values.put("password",password);
        db.insert("userData",null,values);
        db.close();
        return true;
    }
    //检验用户名是否已存在
    public boolean CheckIsDataAlreadyInDBorNot(String value){
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        String Query = "Select * from userData where name =?";
        Cursor cursor = db.rawQuery(Query,new String[] { value });
        if (cursor.getCount()>0){
            cursor.close();
            return  true;
        }
        cursor.close();
        return false;
    }

}


